package io.hellsinger.vortex

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Process
import android.util.Log
import java.util.Calendar

class CrashHandler(
    private val context: Context,
) : Thread.UncaughtExceptionHandler {
    override fun uncaughtException(
        thread: Thread,
        error: Throwable,
    ) {
        val info =
            "SDK: ${Build.VERSION.SDK_INT}\n" +
                "Release: ${Build.VERSION.RELEASE}\n" +
                "Incremental: ${Build.VERSION.INCREMENTAL}\n" +
                "${Calendar.getInstance().time}"

        Log.e("Loggable", "An uncaught exception occurred", error)
        Log.e("Loggable", info)

        val intent = Intent(context, ErrorCatchActivity::class.java)
        intent.putExtra(ErrorCatchActivity.ERROR_KEY, error)
        intent.addFlags(
            Intent.FLAG_ACTIVITY_CLEAR_TASK or
                Intent.FLAG_ACTIVITY_NEW_TASK or
                Intent.FLAG_ACTIVITY_CLEAR_TOP or
                Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS,
        )
        context.startActivity(intent)
        Process.killProcess(Process.myPid())
    }
}
